# -*- coding: utf-8 -*-
#
#
#
require 'rubygems'
require 'net/http'
require 'httpclient'
require 'json'
require 'rexml/document' 
require 'pp'
#
#=== Rakuten API 
class RakutenApiBase

   @developerId =''
   @affiliateId = ''
   @restUrl = ''

   ##
   #
   #=== Rakuten API Initialize
   #
   def initialize(developerId ='' , affiliateId = '' , restUrl='')    #
      
      ras = @@rakuten_settings['general']
      ##
      if developerId == ''
         @developerId = ras['developerId']
      else
         @developerId = developerId
      end

      ##
      if affiliateId == ''
         @affiliateId = ras['affiliateId']
      else
         @affiliateId = affiliateId
      end

      ##
      if restUrl == ''
         @restUrl = ras['restUrl']
      else
         @restUrl = restUrl
      end
   end

	##
	#
	#=== GET METHOD
	#
	def getWebContents(url,args)
		begin
			if !args
				return HTTPClient.new.get_content(url)
			else
				return HTTPClient.new.get_content(url,args)
			end
		rescue
			logger.error('URL:: ' + url )
			logger.error('ARGS:: ' + args.inspect )
			logger.error('error::' + Time.new.strftime("%Y-%m-%d:%H:%M:%S"))
			logger.error($!.message)
			logger.error($!.backtrace[0 .. 10].join("\n"))
			return false
		end	
	end
	##
	#
	#=== POST METHOD
	#
	def postWebContents(url,args)
		begin
			client = HTTPClient.new
			client.ssl_config.verify_mode=(OpenSSL::SSL::VERIFY_NONE)
			return client.post_content(url, args)
		rescue
			logger.error('URL:: ' + url )
			logger.error('ARGS:: ' + args.inspect )
			logger.error('error::' + Time.new.strftime("%Y-%m-%d:%H:%M:%S"))
			logger.error($!.message)
			logger.error($!.backtrace[0 .. 10].join("\n"))
			return false
		end	
	end


	##
	#
	#=== Puts data to file (add)
	#
	def putFileContents(path,data)
			f = File.open(path,"w")
			f.puts data
			f.close
	end

	##
	#
	#=== Convert XML object
	#
	def parseXMLObject(xmltext)
		begin
			doc = REXML::Document.new(xmltext)
			return doc.root
		rescue
			logger.error('xmltext:: ' + xmltext )
			logger.error('error::' + Time.new.strftime("%Y-%m-%d:%H:%M:%S"))
			logger.error($!.message)
			logger.error($!.backtrace[0 .. 10].join("\n"))
			return false
		end
	end
	#
	#=== GenreList
	#
	def self.getGenreList()
		gl={}
		@@rakuten_settings['genretype'].each(){|ras|
			gl.store(ras['id'].to_i,{'id'=>ras['id'].to_i,'name'=>ras['name'] ,'special'=>ras['special'].to_i,'potid'=>ras['potid'].to_i})
		}
		return gl
	end
	##
	#
	#=== Logger
	#
	def logger
		RAILS_DEFAULT_LOGGER
	end
end
